let key = null;
let restore = null;

function encodeBase64(bytes) {
  return btoa(String.fromCharCode(...bytes));
}

function decodeBase64(str) {
  return Uint8Array.from(atob(str), c => c.charCodeAt(0));
}

export function exists(src) {
    key = src;
    restore = localStorage.getItem(src);
    return !!restore;
}

export function readFile(src) {
    if(!src)return null;
    let result=null
    if (src == key) {
        result=restore;
    }else{
        restore=null;
        key=null;
        result=localStorage.getItem(src)
    }
    return decodeBase64(result);
}

export function writeFile(src, data) {
    localStorage.setItem(src, encodeBase64(data));
}

export function filePath(savefileId) {
    if (savefileId < 0) {
        return 'RPG Config';
    } else if (savefileId === 0) {
        return 'RPG Global';
    } else {
        return `RPG File${savefileId}`;
    }
}

export function remove(src){
    localStorage.removeItem(src);
}
